package com.example.service.message.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.example.domain.message.vo.MessageTextVO;
import com.example.manager.MessageCacheManager;
import com.example.mapper.message.MessageTextMapper;
import com.example.service.message.IMessageService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import oj.common.core.contants.JwtConstants;
import oj.common.core.domain.PageQueryDTO;
import oj.common.core.domain.TableDataInfo;
import oj.common.core.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class MessageServiceImpl implements IMessageService {
    @Autowired
    private MessageCacheManager messageCacheManager;
    @Autowired
    private MessageTextMapper messageTextMapper;
    @Override
    public TableDataInfo list(PageQueryDTO pageQueryDTO) {
        Long userId = ThreadLocalUtil.get(JwtConstants.LOGIN_USER_ID,  Long.class);
        Long total = messageCacheManager.getListSize(userId);
        List<MessageTextVO> messageTextVOList;
        if (total == null || total <= 0) {
            //从数据库中查询我的竞赛列表
            PageHelper.startPage(pageQueryDTO.getPageNum(), pageQueryDTO.getPageSize());
            messageTextVOList = messageTextMapper.selectUserMsgList(userId);
            messageCacheManager.refreshCache(userId);
            total = new PageInfo<>(messageTextVOList).getTotal();
        } else {
            messageTextVOList = messageCacheManager.getMsgTextVOList(pageQueryDTO, userId);
        }
        if (CollectionUtil.isEmpty(messageTextVOList)) {
            return TableDataInfo.empty();
        }
        return TableDataInfo.success(messageTextVOList, total);
    }
}
